<template>
  <md-nav-bar title="" :showLeft="false" />
  <view class="container">
    <view class="operation">
      <view class="uni-padding-wrap">
        <uni-segmented-control
          :current="data.current"
          :values="data.items"
          style-type="text"
          :active-color="data.configInfo?.select_color_text || '#1CA4C0'"
          @clickItem="onClickItem" />
      </view>
      <view class="search flex-c">
        <uni-search-bar
          class="uni-mt-10 search-bar"
          radius="40"
          :placeholder="data.current !== 0 ? '请输入队伍名称/编号' : '请输入文章标题'"
          clearButton="auto"
          cancelButton="none"
          v-model="data.value"
          @confirm="handleSearch" />
        <image class="search-icon" :src="data.configInfo?.search_icon" @click="handleSearch" />
      </view>
      <!-- 分享 分类 -->
      <view v-if="data.current === 0" class="tab-btn flex-l">
        <template v-for="item in data.tabBtns" :key="item.value">
          <view
            :class="['tab-btn-item']"
            :style="{
              background: data.currentTab === item.value ? data.configInfo.select_color_text : '#efefef',
              color: data.currentTab === item.value ? '#ffffff' : '#333333',
            }"
            @click="() => handleTabBtn(item.value)">
            {{ item.text }}
          </view>
        </template>
      </view>
      <!-- 组队大厅 分类 -->
      <view v-else class="team-room">
        <uni-forms :modelValue="data.formData" label-width="40">
          <uni-forms-item label="活动" name="active_id">
            <uni-data-select
              placeholder="请选择活动"
              v-model="data.formData.active_id"
              :localdata="data.activeList"
              @change="val => handleClassify(val, 'active_id')"></uni-data-select>
          </uni-forms-item>
          <uni-forms-item label="组别" name="group_id" v-if="data.formData.active_id">
            <uni-data-select
              placeholder="请选择组别"
              v-model="data.formData.group_id"
              :localdata="data.groupList"
              @change="val => handleClassify(val, 'group_id')"></uni-data-select>
          </uni-forms-item>
          <uni-forms-item label="人数" name="num_sorts">
            <uni-data-select
              placeholder="请选择"
              v-model="data.formData.num_sorts"
              :localdata="data.numList"
              @change="val => handleClassify(val, 'num_sorts')" />
          </uni-forms-item>
        </uni-forms>
      </view>
    </view>
    <view class="content">
      <mescroll-body @init="mescrollInit" @down="downCallback" @up="upCallback" :safearea="true" bottom="80px">
        <!-- 分享 -->
        <view v-if="data.current === 0">
          <custom-waterfalls-flow
            v-if="data.list && data.list.length"
            ref="waterfallsFlowRef"
            :value="data.list"
            imageKey="img"
            @wapperClick="handleDetail"
            @imageClick="handleDetail">
            <!-- #ifdef MP-WEIXIN -->
            <view class="flow-item" v-for="(item, index) in data.list" :key="index" slot="slot{{index}}">
              <view class="desc ellipsis-2">{{ item.title }}</view>
              <view class="flex-b m-top-30">
                <view class="flex-l">
                  <image :src="item.avatar" class="head" />
                  <view class="m-left-8">{{ item.nickname }}</view>
                </view>
                <view class="flex-l" @click.stop="() => handleCollect(item)">
                  <md-dianzan :item="item" type="collect" />
                  <view class="m-left-8 fs-28">{{ item.collect_num }}</view>
                </view>
              </view>
            </view>
            <!-- #endif -->
            <!-- #ifndef MP-WEIXIN -->
            <template v-slot:default="item">
              <view class="flow-item">
                <view class="desc ellipsis-2">{{ item.title }}</view>
                <view class="flex-b m-top-30">
                  <view class="flex-l">
                    <image :src="item.avatar" class="head" />
                    <view class="m-left-8">{{ item.nickname }}</view>
                  </view>
                  <view class="flex-l" @click.stop="() => handleCollect(item)">
                    <md-dianzan :item="item" type="collect" />
                    <view class="m-left-8 fs-28">{{ item.collect_num }}</view>
                  </view>
                </view>
              </view>
            </template>
            <!-- #endif -->
          </custom-waterfalls-flow>
        </view>
        <!-- 组队大厅 -->
        <view v-if="data.current === 1">
          <TeamUpList
            :list="data.list"
            :bgUrl="data.configInfo?.team_in"
            :color="data.configInfo?.select_color_text"
            @itemclick="handleListItem" />
        </view>
      </mescroll-body>
    </view>
    <!-- 发布队伍按钮 -->
    <md-icon
      v-if="data.current == 0"
      type="bg"
      :name="data.current === 0 ? 'publish_team' : 'publish_team_up'"
      :url="data.add_hd_icon"
      height="88"
      width="88"
      class="publish-team"
      @click="() => handleTeam(data.current)" />
  </view>
  <!-- 底部导航 -->
  <bottom-tab-bar :selected="3" />
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { onLoad, onPageScroll, onPullDownRefresh, onReachBottom, onShow } from '@dcloudio/uni-app';
// 组件
import TeamUpList from './components/team-up-list.vue';
import useMescroll from '@/uni_modules/mescroll-uni/hooks/useMescroll.js';
// 接口
import { activeIndex, interactionCollect, interactionHall, interactionActiveGroup, interactionIndex } from '@/api';
import type { Interaction } from '@/api/data';
import { stringifyParams, Toast } from '@/utils/util';

const { mescrollInit, downCallback, getMescroll } = useMescroll(onPageScroll, onReachBottom);

const data = reactive<any>({
  list: [],
  items: ['分享', '组队大厅'],
  current: 0,
  value: '',
  onPageScroll,
  onReachBottom,
  canReset: false,
  tabBtns: [
    { text: '全部', value: 0 },
    { text: '我的发布', value: 1 },
  ],
  currentTab: 0,
  add_hd_icon: '', // 互动发布图标
  configInfo: {}, // 全局配置信息
  formData: {
    active_id: '',
    group_id: '',
    num_sorts: '', // 组队人数
  },
  activeList: [],
  groupList: [], // 组队大厅组别列表
  numList: [
    { text: '综合', value: '' },
    { text: '组队人数从多到少', value: 'desc' },
    { text: '组队人数从少到多', value: 'asc' },
  ],
});
const waterfallsFlowRef = ref(null);

// 收藏
const handleCollect = async (item: Interaction.Index.Data) => {
  item.is_collect = !item.is_collect;
  if (!!item.is_collect) {
    item.collect_num += 1;
  } else {
    item.collect_num -= 1;
  }
  const res = await interactionCollect({ id: item.id, collect_type: 1 });
  Toast(res.msg);
};

// 上拉加载的回调: 其中num:当前页 从1开始, size:每页数据条数,默认10
const upCallback = async (mescroll: any) => {
  try {
    let res: any =
      data.current === 0
        ? await interactionIndex({
            page: mescroll?.num || 1,
            limit: mescroll?.size || 10,
            keyword: data.value,
            is_all: data.currentTab,
          })
        : await interactionHall({
            page: mescroll.num,
            limit: mescroll.size,
            keyword: data.value,
            ...data.formData,
          });
    const curPageData = res?.data?.data || []; // 当前页数据
    if (mescroll.num == 1) Object.assign(data, { list: [] }); // 第一页需手动制空列表
    data.list = data.list.concat(curPageData); //追加新数据
    //方法一(推荐): 后台接口有返回列表的总页数 totalPage
    mescroll.endByPage(curPageData.length, res?.data?.total);
  } catch (e) {
    //TODO handle the exception
    mescroll.endErr(); // 请求失败, 结束加载
  }
};

// 组队大厅
const handleListItem = (row: Interaction.Hall.Data) => {
  // console.log(row);
  const query = {
    sign_team_id: row.sign_team_id,
    group_name: row.group_name,
    sign_min_num: row.sign_min_num,
    sign_max_num: row.sign_max_num,
    title: row.title,
    remark: row.remark,
    active_id: row.active_id,
  };
  uni.navigateTo({
    url: `/pages/interact/team-list?params=${stringifyParams(query)}`,
  });
};

// 大tab点击回调
function onClickItem(e: { currentIndex: number }) {
  if (data.current !== e.currentIndex) {
    data.current = e.currentIndex;
    data.list = [];
    // 选中分享，默认全部
    if (e.currentIndex == 0) {
      data.currentTab = 0;
      waterfallsFlowRef.value!.refresh();
    }
    handleSearch();
    data.value = '';
  }
}

// 搜索
function handleSearch() {
  // 回到顶部
  getMescroll()?.scrollTo(0, 0);
  // page重置1请求列表
  getMescroll()?.resetUpScroll();
}

// 小tab点击回调
const handleTabBtn = (val: number) => {
  if (data.currentTab !== val) {
    data.currentTab = val;
    data.list = [];
    waterfallsFlowRef.value!.refresh();
    handleSearch();
    data.value = '';
  }
};

// 跳转互动详情
const handleDetail = (item: any) => {
  const { id } = item;
  uni.navigateTo({
    url: '/pages/interact/i-detail?id=' + id,
  });
};

// 收藏回调
// const handleDianzan = (bool: boolean, id: number) => {
//   const index = data.list.findIndex(item => item.id === id);
//   data.list[index].selected = bool;
// };

// 组队回调
const handleTeam = (type: number) => {
  if (type === 0) {
    // 分享
    uni.navigateTo({
      url: '/pages/interact/create',
    });
  } else {
    // 组队大厅
  }
};

// 选中回调
const handleClassify = (val: any, type: string) => {
  if (type === 'active_id') {
    if (val) {
      data.formData.group_id = ''; // 清空组别
      getActiveGroupList(val); // 获取组队大厅分组列表
    } else {
      data.groupList = []; // 清空组别列表
    }
    data.formData.active_id = val;
  }
  if (type === 'group_id') {
    data.formData.group_id = val;
  }
  if (type === 'num_sorts') {
    data.formData.num_sorts = val;
  }
  getMescroll()?.resetUpScroll(); // 重置列表数据为第一页
  getMescroll()?.scrollTo(0, 0); // 重置列表数据为第一页时,建议把滚动条也重置到顶部,避免无法再次翻页的问题
};

// 获取活动列表
const getActiveList = async () => {
  try {
    const res = await activeIndex({ page: 1, limit: 100, type: 1 });
    data.activeList = res?.data?.data?.map(item => ({ text: item.title, value: item.id })) || [];
  } catch (e) {
    //TODO handle the exception
    console.error(e);
  }
};

// 通过活动ID获取组队大厅分组列表
const getActiveGroupList = async (active_id: string) => {
  try {
    const res = await interactionActiveGroup({ active_id });
    let list = [];
    for (let [value, text] of Object.entries(res?.data || {})) {
      list.push({ text, value });
    }
    data.groupList = list;
  } catch (e) {
    //TODO handle the exception
    console.error(e);
  }
};

onLoad(() => {
  const configInfo = uni.getStorageSync('configInfo') ? JSON.parse(uni.getStorageSync('configInfo')) : '';
  if (configInfo) {
    data.add_hd_icon = configInfo.add_hd_icon;
    data.configInfo = configInfo;
  }
  // 活动列表
  getActiveList();
});

onShow(() => {
  // data.canReset && getMescroll().resetUpScroll(); // 重置列表数据为第一页
  // data.canReset && getMescroll().scrollTo(0, 0); // 重置列表数据为第一页时,建议把滚动条也重置到顶部,避免无法再次翻页的问题
  // data.canReset = true; // 过滤第一次的onShow事件,避免初始化界面时重复触发upCallback, 无需配置auto:false
});

onPullDownRefresh(() => {
  getMescroll()?.resetUpScroll();
  setTimeout(() => {
    uni.stopPullDownRefresh();
  }, 300);
});
</script>
<style lang="scss" scoped>
.container {
  .operation {
    position: sticky;
    top: calc($safe-top + 44px);
    z-index: 10;
    background: white;
    ::v-deep .uni-forms-item {
      margin-bottom: 20rpx;
    }
    ::v-deep .uni-forms-item__label {
      font-weight: bold;
      color: #ffa500;
    }
    // 组队大厅
    .team-room {
      width: 100%;
      padding: 0 20rpx 2rpx 20rpx;
      box-sizing: border-box;
    }
    ::v-deep .uni-forms-item__content {
      min-width: 0;
    }
    ::v-deep .uni-select__input-box {
      width: 100%;
    }
  }
  .uni-padding-wrap {
    padding-bottom: 20rpx;
  }
  background: white;
  .content {
    background: $backColor;
    padding: 20rpx 30rpx 0 30rpx;
    .flow-item {
      padding: 8rpx;
      .head {
        width: 40rpx;
        height: 40rpx;
        border-radius: 50%;
        background: $primary;
      }
    }
  }
  .search {
    width: 100%;
    padding: 0 30rpx;
    box-sizing: border-box;
    .search-bar {
      flex: 1;
    }
  }
  .search-icon {
    width: 88rpx;
    height: 65rpx;
    cursor: pointer;
  }

  .tab-btn {
    padding: 0 30rpx 20rpx;
    box-sizing: border-box;
    &-item {
      &:not(:last-of-type) {
        margin-right: 20rpx;
      }
      width: 140rpx;
      height: 50rpx;
      line-height: 50rpx;
      border-radius: 25rpx;
      background: #efefef;
      color: $title;
      text-align: center;
      &.active {
        background: #1ca4c0;
        color: white;
      }
    }
  }

  // 分页列表
  .pagelist {
    background: $backColor;
    .card {
      &:not(:last-of-type) {
        margin-bottom: 20rpx;
      }
      background: white;
      padding: 35rpx 30rpx 20rpx;
      position: relative;
      .hot-icon.position {
        top: -30rpx;
        left: -16rpx;
      }
      .image {
        position: relative;
        width: 690rpx;
        height: 320rpx;
        border-radius: 0rpx 0rpx 20rpx 20rpx;
        overflow: hidden;
        .mask {
          width: 100%;
          height: 60rpx;
          position: absolute;
          bottom: 0;
          left: 0;
          background: rgba(0, 0, 0, 0.5);
          &-date {
            font-size: $fs-28;
            color: #ffffff;
            line-height: 60rpx;
            padding: 0 32rpx;
          }
        }
      }
      .text {
        font-size: $fs-34;
        color: $title;
        font-weight: bold;
      }
      .date {
        text-align: right;
        color: $sub;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        .clock {
          width: 30rpx;
          height: 30rpx;
        }
      }
    }
  }

  .publish-team {
    position: fixed;
    right: 16rpx;
    bottom: calc(80px + $safe-bottom + 80px);
  }
}
</style>
